package com.lsh.netty.http.xml;

import com.thoughtworks.xstream.XStream;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/6/8 12:20 下午
 * @desc ： HTTP + XML 请求消息编码基类
 */
@Slf4j
public abstract class AbstractHttpXmlEncoder<T> extends MessageToMessageEncoder<T> {
    final static  String CHARSET_NAME = "UTF-8";
    final static Charset UTF_8 = Charset.forName(CHARSET_NAME);

    protected ByteBuf encode0(ChannelHandlerContext ctx,Object body)throws  Exception{
        // 将Order类转换为xml流
        XStream xStream = new XStream();
        // 1001
        xStream.setMode(XStream.NO_REFERENCES);
        // 注册使用了注解的VO
        xStream.processAnnotations(new Class[] { Order.class, Customer.class, Shipping.class, Address.class });
        String xmlStr = xStream.toXML(body);
//        log.info("Java对象转XML："+xmlStr);
        ByteBuf byteBuf = Unpooled.copiedBuffer(xmlStr, UTF_8);
        return byteBuf;

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("消息编码失败");
    }
}
